/* Esptouch example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "tcpip_adapter.h"
#include "esp_smartconfig.h"
#include "smartconfig_ack.h"
#include "app_smartconfig.h"
#include "app_main.h"

/* The examples use smartconfig type that you can set via project configuration menu.

   If you'd rather not, just change the below entries to enum with
   the config you want - ie #define EXAMPLE_ESP_SMARTCOFNIG_TYPE SC_TYPE_ESPTOUCH
*/
#define EXAMPLE_ESP_SMARTCOFNIG_TYPE      SC_TYPE_ESPTOUCH_AIRKISS

/* FreeRTOS event group to signal when we are connected & ready to make a request */


/* The event group allows multiple bits for each event,
   but we only care about one event - are we connected
   to the AP with an IP? */

static const char* TAG = "smartconfig_example";

static void smartconfig_example_task(void* parm);


void initialise_wifi(void)
{
    s_wifi_event_group = xEventGroupCreate();
	s_device_event_group = xEventGroupCreate();
	
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();

    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));

    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_start());
}

static void smartconfig_example_task(void* parm)
{
    EventBits_t uxBits;
	esp_wifi_disconnect();
	ESP_LOGI(TAG, "esp_wifi_disconnect");
    ESP_ERROR_CHECK(esp_smartconfig_set_type(EXAMPLE_ESP_SMARTCOFNIG_TYPE));
    smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_smartconfig_start(&cfg));

	xEventGroupSetBits(s_device_event_group, SMARTCONFIG_MODE_BIT);
	
    while (1) {
        uxBits = xEventGroupWaitBits(s_wifi_event_group, ESPTOUCH_DONE_BIT, true, false, portMAX_DELAY);

        if (uxBits & CONNECTED_BIT) {
            ESP_LOGI(TAG, "WiFi Connected to ap");
        }

        if (uxBits & ESPTOUCH_DONE_BIT) {
            ESP_LOGI(TAG, "smartconfig over");
            esp_smartconfig_stop();
			xEventGroupClearBits(s_device_event_group, SMARTCONFIG_MODE_BIT);
            vTaskDelete(NULL);
        }
    }
}
/**
  * @brief  Main.
  * @param  None.
  * @retval None.
  */
void smartconfig_start( void )
{
	xTaskCreate(smartconfig_example_task, "smartconfig_example_task", 8192, NULL, 3, NULL);
}


